package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 设备数据管理Service业务层处理
 *
 * @author zjx
 * @date 2025-05-25
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 查询设备数据管理列表
     *
     * @param deviceData 设备数据管理
     * @return 设备数据管理
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }



    /**
     * 基于IOT设备上传通知的数据，批量保存设备数据
     *
     * @param
     */
    @Override
    public void saveDeviceData(String contentStr) {
        //1.判断参数是否为空
        if (StringUtils.isBlank(contentStr)) {
            throw new BaseException("参数非法");
        }

        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        if(jsonObject==null){
            return;
        }

        JSONObject notifyDataObject = jsonObject.getJSONObject("notify_data");
        if(notifyDataObject==null){
            return;
        }
        JSONObject header = notifyDataObject.getJSONObject("header");
        if (header == null) {
            throw new BaseException("参数非法");
        }
        JSONObject body = notifyDataObject.getJSONObject("body");
        if (body == null) {
            throw new BaseException("参数非法");
        }
        IotMsgNotifyData notifyData = JSONUtil.toBean(notifyDataObject,IotMsgNotifyData.class);

//        IotMsgNotifyData iotMsgNotifyData = JSONObject.parseObject(notifyData.toJSONString(), IotMsgNotifyData.class);
        //2.获取设备信息
        String deviceId = notifyData.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        //3.判断设备是否存在
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        //4.准备设备数据
        List<IotMsgService> services = notifyData.getBody().getServices();
        List<DeviceData> list = new ArrayList<>();
        services.forEach(x -> {
            String eventTime = x.getEventTime();
            LocalDateTime alarmTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            x.getProperties().forEach((k,v)->{
                DeviceData deviceData = new DeviceData();
                BeanUtils.copyProperties(device, deviceData);
                deviceData.setId(null);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(k);
                deviceData.setDataValue(String.valueOf(v));
                deviceData.setAlarmTime(alarmTime);
                list.add(deviceData);
            });
        });
        //5.批量保存设备数据
            //判断设备数据集合是否为空
        if(CollUtil.isNotEmpty(list)){
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_DATA_LIST, deviceId, JSONUtil.toJsonStr(list));
            boolean result = this.saveBatch(list);
            if(!result){
                throw new BaseException("保存设备数据信息失败");
            }
        }
    }
}
